<?php
/***
* @version $Id: admin_blocks.php 336 2007-01-23 08:12:56Z flexiondotorg $
* @copyright (c) 2006 - 2007 Flexion.Org
*            (c) 2004 - 2005 Project Minerva
*            (c) 2001 - 2006 phpBB Group
* @license   http://opensource.org/licenses/gpl-license.php GNU Public License
***/

define('IN_R3BORN', true);

if( !empty($setmodules) )
{
    $module['Modules']['Block_placement'] = basename(__FILE__);
    return;
}

//
// Load default header
//
$root_path = './../';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
require('./pagestart.' . $phpEx);
include_once($root_path. 'includes/functions_selects.' . $phpEx);

$mode = get_var('mode', '');

if ($mode == '')
{
    //
    // These could be entered via a form button
    //
    if( isset($_POST['add']) )
    {
        $mode = 'add';
    }
    else if( isset($_POST['save']) )
    {
        $mode = 'save';
    }
    else
    {
        $mode = '';
    }
}

if(isset($_POST['cancel']))
{
    $mode = '';
}

if( $mode != '' && $mode != 'blocks' )
{
    if( $mode == 'edit' || $mode == 'add' )
    {
        $block_id = get_var('block_id', 0);
        $layout_id = get_var('layout_id', 0);
        $module_id = get_var('module_id', 0);

        $block_groups = array();
        $block_row = array();

        $s_hidden_fields = '';

        $template->set_filenames(array(
            'body' => 'blocks_edit_body.tpl')
        );

        $s_hidden_fields .= '<input type="hidden" name="layout_id" value="' . $layout_id . '" />';

        $message='';

        if( $mode == 'edit' )
        {
            if( $block_id )
            {
                $sql = "SELECT *
                    FROM " . BLOCKS_TABLE . "
                    WHERE block_id = $block_id";
                if(!$result = $db->sql_query($sql))
                {
                    message_die(GENERAL_ERROR, "Could not query blocks table", "Error", __LINE__, __FILE__, $sql);
                }

                $block_row = $db->sql_fetchrow($result);
                $db->sql_freeresult($result);

                $block_groups = explode(',', $block_row['groups']);

                $s_hidden_fields .= '<input type="hidden" name="block_id" value="' . $block_id . '" />';
            }
            else
            {
                message_die(GENERAL_MESSAGE, $lang['No_blocks_selected']);
            }
        }

		$block_position = array(
			BLOCK_TOP => $lang['Block_top'],
			BLOCK_LEFT => $lang['Block_left'],
			BLOCK_RIGHT  => $lang['Block_right'],
			BLOCK_BOTTOM  => $lang['Block_bottom']
		);

		$position_list ='<select name="block_position" class="post">';
		for ($i = 1; $i <= count($block_position); $i++)
		{
			$position_list .= '<option value="' . $i .'" ';
			if($block_row['block_position'] == $i)
			{
				$position_list .= 'selected="selected"';
			}
			$position_list .= '>' . $block_position[$i];
		}
		$position_list .= '</select>';

		// Populate the block code (module_id) selection list
		// If we are editting a layout, just display the layout name.

		$block_list = '';

		if ($mode == 'edit')
		{
			foreach ($mvModules as $name => $value)
			{
				if ( ($value['state'] == MODULE_ENABLED || $value['state'] == MODULE_DEFAULT) && $value['type'] == ADDON_BLOCK )
				{
					if ($module_id == $value['id'])
					{
						$block_list = $value['displayname'];
					}
				}
			}
		}
		else
		{
			$active_blocks = 0;
			$block_list = '<select name="module_id" class="post">';
			foreach ($mvModules as $name => $value)
			{
				if ( ($value['state'] == MODULE_ENABLED || $value['state'] == MODULE_DEFAULT) && $value['type'] == ADDON_BLOCK )
				{
					$block_list .= '<option value="' . $value['id'] .'" ';
					$block_list .= '>' . $value['displayname'];
					$active_blocks++;
				}
			}
			$block_list .= '</select>';

			if ($active_blocks == 0)
    	    {
	    	   	$message = $lang['No_active_blocks'];
		       	$message .= "<br /><br />" . sprintf($lang['Click_return_blockadmin'], "<a href=\"" . append_sid("admin_blocks.$phpEx") . "\">", "</a>") . "<br /><br />" . sprintf($lang['Click_return_admin_index'], "<a href=\"" . append_sid("index.$phpEx?pane=right") . "\">", "</a>");
    	    	message_die(GENERAL_MESSAGE, $message);
	    	}
		}

		$viewlist 	= user_auth_select($block_row['block_view'], 'block_view');
		$grouplist 	= group_auth_select($block_groups);

        $template->assign_vars(array(
            'L_BLOCKS_TITLE' => $lang['Blocks_Title'],
            'L_BLOCKS_TEXT' => $lang['Blocks_Explain'],
            'L_B_POSITION' => $lang['B_Position'],
            'L_B_BLOCKFILE' => $lang['Block_block'],
            'L_B_VIEW_BY' => $lang['User_Level'],
            'L_B_GROUP' => $lang['Usergroups'],
            'POSITION' => $position_list,
            'BLOCKFILE' => $block_list,
            'VIEWBY' => $viewlist,
            'GROUP' => $grouplist,

            'L_EDIT_BLOCK' => $lang['Block_Edit'],
            'L_SUBMIT' => $lang['Submit'],
            'S_BLOCKS_ACTION' => append_sid('admin_blocks.' . $phpEx),
            'S_HIDDEN_FIELDS' => $s_hidden_fields)
        );

        $template->pparse('body');

        page_footer_admin();
    }
    else if( $mode == 'save' )
    {
        $block_id = get_var('block_id', 0);
        $layout_id = get_var('layout_id', 0);
        $module_id = get_var('module_id', 0);
        $block_position = get_var('block_position', 0);
        $block_view = get_var('block_view', 0);

        // Validate input
		if ($block_position == 0)
        {
            message_die(GENERAL_MESSAGE, $lang['Block_details_incomplete']);
        }

        $block_groups = prepare_group_list();

        if( $block_id )
        {
            $sql = "UPDATE " . BLOCKS_TABLE . " SET
                block_position = '" . str_replace("\'", "''", $block_position) . "',
                block_view = '" . $block_view . "',
                groups = '" . $block_groups . "'
                WHERE block_id = $block_id";

            if(!$result = $db->sql_query($sql))
            {
                message_die(GENERAL_ERROR, 'Could not insert data into blocks table', $lang['Error'], __LINE__, __FILE__, $sql);
            }

            $message = $lang['Block_updated'];
        }
        else
        {
            $sql = "SELECT max(block_weight) mweight FROM " . BLOCKS_TABLE . " WHERE layout_id ='" . $layout_id . "' AND block_position ='" . $block_position . "'";
            if(!$result = $db->sql_query($sql))
            {
                message_die(GENERAL_ERROR, 'Could not query from blocks table', $lang['Error'], __LINE__, __FILE__, $sql);
            }

            $row = $db->sql_fetchrow($result);
            $weight = $row['mweight'];

            $sql = "INSERT INTO " . BLOCKS_TABLE . " (block_position, block_weight, block_view, groups, layout_id, module_id) VALUES ('" . $block_position . "', '" . $weight . "', '" . $block_view . "', '" . $block_groups . "', '" . $layout_id . "', '" . $module_id . "')";

            $message = $lang['Block_added'];

            if(!$result = $db->sql_query($sql))
            {
                message_die(GENERAL_ERROR, 'Could not insert data into blocks table', $lang['Error'], __LINE__, __FILE__, $sql);
            }
        }
        reorderBlocks($layout_id);

        $message .= "<br /><br />" . sprintf($lang['Click_return_blockadmin'], "<a href=\"" . append_sid("admin_blocks.$phpEx?mode=blocks&amp;layout_id=$layout_id") . "\">", "</a>") . "<br /><br />" . sprintf($lang['Click_return_admin_index'], "<a href=\"" . append_sid("index.$phpEx?pane=right") . "\">", "</a>");
        message_die(GENERAL_MESSAGE, $message);
    }
    else if( $mode == 'delete' )
    {
		$block_id = get_var('block_id',0);
		$layout_id = get_var('layout_id',0);

		if(!isset($_POST['confirm']))
		{
			$hidden_fields = '<input type="hidden" name="mode" value="'.$mode.'" /><input type="hidden" name="block_id" value="'.$block_id.'" /><input type="hidden" name="layout_id" value="'.$layout_id.'" />';

			//
			// Set template files
			//
			$template->set_filenames(array(
				'confirm' => 'confirm_body.tpl')
			);

			$template->assign_vars(array(
				'MESSAGE_TITLE' => $lang['Confirm'],
				'MESSAGE_TEXT' => $lang['Confirm_delete_item'],

				'L_YES' => $lang['Yes'],
				'L_NO' => $lang['No'],

				'S_CONFIRM_ACTION' => append_sid('admin_blocks.' . $phpEx),
				'S_HIDDEN_FIELDS' => $hidden_fields)
			);

			$template->pparse('confirm');
			exit();
		}
		else
		{
			if( $block_id )
			{
				$sql = "DELETE FROM " . BLOCKS_TABLE . " WHERE block_id = $block_id";

				if(!$result = $db->sql_query($sql))
				{
					message_die(GENERAL_ERROR, 'Could not remove data from blocks table', $lang['Error'], __LINE__, __FILE__, $sql);
				}

				$message = $lang['Block_removed'] . "<br /><br />" . sprintf($lang['Click_return_blockadmin'], "<a href=\"" . append_sid("admin_blocks.$phpEx?mode=blocks&amp;layout_id=$layout_id") . "\">", "</a>") . "<br /><br />" . sprintf($lang['Click_return_admin_index'], "<a href=\"" . append_sid("index.$phpEx?pane=right") . "\">", "</a>");

				message_die(GENERAL_MESSAGE, $message);
			}
			else
			{
				message_die(GENERAL_MESSAGE, $lang['No_blocks_selected']);
			}
			reorderBlocks($layout_id);
		}
	}
}
else if ($mode == 'blocks')
{
    $template->set_filenames(array(
        'body' => 'blocks_list_body.tpl')
    );

    $layout_id = get_var('layout_id', 0);
    $move = get_var('move', -1);

    if( $move == '0' || $move == '1' )
    {
        $block_id = get_var('block_id', 0);
        $block_weight = get_var('weight', 0);
        $block_position = get_var('pos', 0);

        if( ($move == '1' && $block_weight != '1' && $block_weight != '0') || ( $move == '0' && $block_weight != '0' ) )
        {
            if( $move == '1')
            {
                $temp = $block_weight-1;
            }
            else
            {
                $temp = $block_weight+1;
            }
            $sql = "UPDATE " . BLOCKS_TABLE . " SET block_weight = '" . $block_weight . "' WHERE layout_id = '" . $layout_id . "' AND block_weight = '" . $temp . "' AND block_position = '" . $block_position . "'";
            if(!$result = $db->sql_query($sql))
            {
                message_die(GENERAL_ERROR, 'Could not update data in blocks table', $lang['Error'], __LINE__, __FILE__, $sql);
            }
            $sql = "UPDATE " . BLOCKS_TABLE . " SET block_weight = '" . $temp . "' WHERE block_id = '" . $block_id . "'";
            if(!$result = $db->sql_query($sql))
            {
                message_die(GENERAL_ERROR, 'Could not update data in blocks table', $lang['Error'], __LINE__, __FILE__, $sql);
            }
            reorderBlocks($layout_id);
        }
    }

    $sql = "SELECT layout_url FROM " . LAYOUT_TABLE . " WHERE layout_id ='" . $layout_id . "'";
    if( !$result = $db->sql_query($sql) )
    {
        message_die(GENERAL_ERROR, 'Could not query layout table', $lang['Error'], __LINE__, __FILE__, $sql);
    }
    $layout_name_row = $db->sql_fetchrow($result);

    $layout_name = $layout_name_row['layout_url'];

    $sql = "SELECT * FROM " . BLOCKS_TABLE . " WHERE layout_id = '" . $layout_id . "' ORDER BY block_position, block_weight";
    if( !$result = $db->sql_query($sql) )
    {
        message_die(GENERAL_ERROR, 'Could not query blocks table', $lang['Error'], __LINE__, __FILE__, $sql);
    }

    $block_rows = $db->sql_fetchrowset($result);

    $s_hidden_fields .= '<input type="hidden" name="layout_id" value="' . $layout_id . '" />';

    $template->assign_vars(array(
        'L_BLOCKS_TITLE' => $lang['Blocks_Title'],
        'L_BLOCKS_TEXT' => $lang['Blocks_Explain'],
        'L_BLOCK_POSITION' => $lang['B_Position'],
        'L_BLOCK_NAME' => $lang['Block_block'],

		'LAYOUT_NAME' => $layout_name,

        'L_BLOCK_VIEW' => $lang['User_Level'],
        'L_BLOCK_GROUPS' => $lang['Usergroups'],
        'L_ACTION' => $lang['Action'],
        'L_BLOCKS_ADD' => $lang['B_Add'],
        'L_EDIT' => $lang['Edit'],
        'L_DELETE' => $lang['Delete'],
        'L_MOVE_UP' => $lang['Move_up'],
        'L_MOVE_DOWN' => $lang['Move_down'],
        'S_BLOCKS_ACTION' => append_sid('admin_blocks.' . $phpEx),
        'S_HIDDEN_FIELDS' => $s_hidden_fields)
    );

	$block_positions = array(
		BLOCK_TOP => $lang['Block_top'],
		BLOCK_LEFT => $lang['Block_left'],
		BLOCK_RIGHT  => $lang['Block_right'],
		BLOCK_BOTTOM  => $lang['Block_bottom']
	);

	for ($i = 0; $i <= count($block_positions); $i++)
	{
		$position_list[] = $block_positions[$i];
	}

    for($i = 0; $i < count($block_rows); $i++)
    {

        $block_id = $block_rows[$i]['block_id'];
        $module_id = $block_rows[$i]['module_id'];
        $block_weight = $block_rows[$i]['block_weight'];
        $block_position = $block_rows[$i]['block_position'];

        $block_name = '';
		foreach ($mvModules as $name => $value)
		{
			if ( ($value['state'] == MODULE_ENABLED || $value['state'] == MODULE_DEFAULT) && $value['type'] == ADDON_BLOCK )
			{
				if ($module_id == $value['id'])
				{
					$block_name = $value['displayname'];
				}
			}
		}

		$row_class = ( !($i % 2) ) ? 'row1' : 'row2';

        switch ($block_rows[$i]['block_view'])
        {
            case '0':
                $block_view = $lang['All'];
                break;
            case '1':
                $block_view = $lang['Guests'];
                break;
            case '2':
                $block_view = $lang['Reg'];
                break;
            case '3':
                $block_view = $lang['Owner'];
                break;
            case '4':
                $block_view = $lang['Admin'];
                break;
        }

        if(!empty($block_rows[$i]['groups']))
        {
            $sql = "SELECT group_name FROM " . GROUPS_TABLE . " WHERE group_id in (" . $block_rows[$i]['groups'] . ")";
            if( !($result = $db->sql_query($sql)) )
            {
                message_die(CRITICAL_ERROR, "Could not query user groups information", "", __LINE__, __FILE__, $sql);
            }
            $groups = '';
            while ($row = $db->sql_fetchrow($result))
            {
                    $groups .= '&nbsp;' . $row['group_name'] . '&nbsp;';
            }
        }
        else
        {
            $groups = $lang['All'];
        }


        $template->assign_block_vars("blocks", array(
            'ROW_CLASS' => $row_class,
            'NAME' => $block_name,
            'POSITION' => $position_list[$block_position],
			'VIEW' => $block_view,
            'GROUPS' => $groups,
            'U_EDIT' => append_sid("admin_blocks.$phpEx?mode=edit&amp;block_id=$block_id&amp;layout_id=$layout_id&amp;module_id=$module_id"),
            'U_DELETE' => append_sid("admin_blocks.$phpEx?mode=delete&amp;block_id=$block_id&amp;layout_id=$layout_id"),
            'U_MOVE_UP' => append_sid("admin_blocks.$phpEx?mode=blocks&amp;layout_id=$layout_id&amp;move=1&amp;block_id=$block_id&amp;weight=$block_weight&amp;pos=$block_position"),
            'U_MOVE_DOWN' => append_sid("admin_blocks.$phpEx?mode=blocks&amp;layout_id=$layout_id&amp;move=0&amp;block_id=$block_id&amp;weight=$block_weight&amp;pos=$block_position")
            )
        );
    }
}
else
{
    $template->set_filenames(array(
        "body" => "blocks_layout_list_body.tpl")
    );

    $sql = "SELECT *
    		FROM " . LAYOUT_TABLE . "
        	ORDER BY module_id";
    if( !$result = $db->sql_query($sql) )
    {
        message_die(GENERAL_ERROR, "Could not query layout table", $lang['Error'], __LINE__, __FILE__, $sql);
    }

    $layout_rows = $db->sql_fetchrowset($result);

    $template->assign_vars(array(
        "L_BLOCKS_TITLE" => $lang['Blocks_Title'],
        "L_BLOCKS_TEXT" => $lang['Blocks_Explain'],
        "L_CHOOSE_LAYOUT" => $lang['Choose_Layout'],
        "S_BLOCKS_ACTION" => append_sid('admin_blocks.' . $phpEx),
        "S_HIDDEN_FIELDS" => '')
    );

    for($i = 0; $i < count($layout_rows); $i++)
    {

        $layout_id = $layout_rows[$i]['layout_id'];

		foreach ($mvLayouts as $url => $mvLayout)
		{
			if ($url == $layout_rows[$i]['layout_url'])
			{
				$layout_name = $mvLayout['name'];
				break;
			}
		}

        $row_class = ( !($i % 2) ) ? 'row1' : 'row2';

        $template->assign_block_vars("layout", array(
            "ROW_CLASS" => $row_class,
			"NAME" => $layout_name,
            "U_LAYOUT" => append_sid('admin_blocks.' . $phpEx . '?mode=blocks&amp;layout_id=' . $layout_id)
            )
        );
    }
}

$template->pparse("body");

page_footer_admin();

?>